package com.framework.modules.base.controller;

import com.alibaba.fastjson.JSONObject;
import com.framework.common.config.SystemConfigName;
import com.framework.common.consts.RedisConstKey;
import com.framework.common.live.TencentLiveKit;
import com.framework.common.message.MessagePacketData;
import com.framework.common.message.MessageType;
import com.framework.common.oss.CloudStorageService;
import com.framework.common.oss.OSSFactory;
import com.framework.common.model.config.ConfigPaymentRateMoney2Coin;
import com.framework.common.sms.SmsResponse;
import com.framework.common.utils.*;
import com.framework.config.DatabaseInitConfig;
import com.framework.modules.base.entity.UserInfoEntity;
import com.framework.modules.base.service.UserInfoService;
import com.framework.modules.base.service.UserService;
import com.framework.modules.base.service.ValidateCodeService;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.live.v20180801.LiveClient;
import com.tencentcloudapi.live.v20180801.models.DescribeStreamPlayInfoListRequest;
import com.tencentcloudapi.live.v20180801.models.DescribeStreamPlayInfoListResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.framework.common.annotation.Login;
import com.framework.common.annotation.LoginUser;
import com.framework.modules.base.entity.UserEntity;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@RestController
@RequestMapping("/test")
@Api(tags = "测试接口")
public class ApiTestController {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private UserService userService;

	@Autowired
	private UserInfoService userInfoService;

	@Autowired
	private ValidateCodeService validateCodeService;

	@Autowired
	private RedisUtils redisUtils;



	@Login
	@GetMapping("userInfo")
	@ApiOperation(value = "获取用户信息", response = UserEntity.class)
	public R userInfo() {
		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

		HttpServletRequest request = servletRequestAttributes.getRequest();
		Object object = request.getAttribute(HttpContextUtils.USER_KEY);
		if (object == null) {
			return R.error("没有获取到用户信息");
		}

		// 获取用户信息
		UserEntity user = userService.selectById((Long) object);
		return R.ok().put("user", user);
	}

	@Login
	@GetMapping("userId")
	@ApiOperation("获取用户ID")
	public R userInfo(@ApiIgnore @RequestAttribute("userId") Integer userId) {
		return R.ok().put("userId", userId);
	}

	@GetMapping("get_current_token")
	@ApiOperation("获取当前token")
	public R getCurrentToken() {
		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = servletRequestAttributes.getRequest();
		Map<String, String> map = new HashMap<String, String>();
		map.put("token", request.getHeader("token"));
		return R.ok().put("msg", map);
	}

	@GetMapping("notToken")
	@ApiOperation("忽略Token验证测试")
	public R notToken() {
		return R.ok().put("msg", "无需token也能访问。。。");
	}

	@Login
	@ResponseBody
	@GetMapping("other_module")
	@ApiOperation("测试其他模块")
	public R ref_admin_module(@RequestParam Map<String, Object> params) {
		PageUtils page = userInfoService.queryPage(params);
		return R.ok().put("page", page);
	}

	@RequestMapping("helloworld")
	@ApiOperation("测试接口helloworld")
	public R helloworld(@RequestParam(value = "action", defaultValue = "") String action) {

		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = servletRequestAttributes.getRequest();
		HttpServletResponse response = servletRequestAttributes.getResponse();
		Map<String, String[]> params = request.getParameterMap();
		String date = DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
		String msg = String.format("access successed ,  the server time is %s", date);
		Object[] obj = {msg, params};

//		if ("write".equals(action)) {
//			DatabaseInitConfig.reloadConfig();
//			//SensitiveWordsInit.reload();
//		}

		Map<String, Object> data = new LinkedHashMap<>();
		data.put("date", date);
		data.put("state", msg);
		data.put("debug", QuickHelper.getConfigValue(SystemConfigName.DEBUG, String.class));

		return R.ok().put("data", data);
	}

	@PostMapping(value = "post")
	@ApiOperation("测试Form POST")
	public R test_post(@RequestBody Map<String, Object> params) {
		return R.ok().put("code", 1).put("posts", params);
	}

	@PostMapping(value = "get")
	@ApiOperation("测试QueryString Get")
	public R test_get(@RequestBody Map<String, Object> params) {
		return R.ok().put("code", 1).put("gets", params);
	}

	@GetMapping(value = "test_show_env")
	@ApiOperation("查看环境变量")
	public R test_show_env(@RequestParam Map<String, Object> params) {
		return R.ok().put("code", 1).put("msg", "aa");
	}


	@PostMapping(value = "test_send_sms")
	@ApiOperation("测试发送短信接口")
	public R test_send_sms(String mobile) {
		Integer rnd = QuickHelper.get_random_code(600000, 999999);
		SmsResponse res = validateCodeService.sendValidateCode(mobile, rnd.toString());
		return R.ok().put("code", 1).put("msg", res.getRawResponseObject());
	}

	@PostMapping(value = "test_oss_upload")
	@ApiOperation("测试OSS上传")
	public R test_oss_upload(@RequestParam("file") MultipartFile file) {
		if (file == null) {
			return R.error(-1, "请选择一个文件");
		}

		try {
			CloudStorageService service = OSSFactory.create();
			String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			String path = QuickHelper.createCloudStorageFileName(suffix, OSSFactory.DirectoryConfig.getTemp());
			String url = service.upload(file.getBytes(), path).getUrl();
			return R.ok("调用完成，并未入库").put("url", url);
		} catch (Exception e) {
			return R.error("上传失败：" + e.getMessage());
		}
	}

	@GetMapping(value = "test_get_push_url")
	@ApiOperation("获取推流地址")
	public R test_get_push_url(String name) {

		String domain = "push.minglianshua.com";
		String key = "79c85dd1098a5e7d014f97d79a0b0000";
		Integer expiredSeconds = DateUtils.getSecondTimestamp(new Date()) + 10 * 60 * 1000;
		String url = TencentLiveKit.getPushUrl(domain, key, name, expiredSeconds);

		return R.ok("获取成功").put("url", url);
	}

	@GetMapping(value = "test_get_play_url")
	@ApiOperation("获取播放地址")
	public R test_get_play_url(String name) {

		String domain = "push.minglianshua.com.livepush.myqcloud.com";
		String key = "79c85dd1098a5e7d014f97d79a0b0000";
		Integer expiredSeconds = DateUtils.getSecondTimestamp(new Date()) + 10 * 60 * 1000;
		Map<String, String> map = new HashMap<>();
		map.put("FLV", "http://play.minglianshua.com/live/" + name + ".flv");
		map.put("RTMP", "rtmp://play.minglianshua.com/live/" + name);
		map.put("HLS", "http://play.minglianshua.com/live/" + name + ".m3u8");
		map.put("UDP", "webrtc://play.minglianshua.com/live/" + name);
		return R.ok(map);
	}

	@Login
	@GetMapping(value = "test_login_user")
	@ApiOperation("测试登陆用户注解")
	public R test_login_user(@LoginUser UserEntity entity) {
		return R.ok(entity);
	}

	@GetMapping(value = "show_payment_rate")
	@ApiOperation("查看现金和金币兑换比例")
	public R test_login_user() {
		ConfigPaymentRateMoney2Coin prm = QuickHelper.getConfigValue(SystemConfigName.PAY_RATE_MONEY2COIN, ConfigPaymentRateMoney2Coin.class);
		return R.ok(prm);
	}

	@GetMapping(value = "show_response_code")
	@ApiOperation("测试返回码")
	public R show_response_code() {
		ResponseCode[] codes = ResponseCode.values();
		Map<String, String> maps = new HashMap<>();
		for (ResponseCode code : codes) {
			maps.put(code.toString(), String.format("%s (%s)", code.getDesc(), code.getCode()));
		}
		return R.response(ResponseCode.NONE).put("data", maps);
	}

	@Login
	@GetMapping(value = "send_gift_item_to_redis")
	@ApiOperation("测试礼物发送")
	public R send_gift_item_to_redis() {
		Long uid = HttpContextUtils.getHttpServletRequestHeaderUserid();
		UserInfoEntity userinfo = (UserInfoEntity) userInfoService.getInfo(uid, "info");

		String key1 = RedisConstKey.REDIS_PROXY_MESSAGE_KEY;
		String key2 = RedisConstKey.REDIS_PROXY_MESSAGE_HISTORY_KEY;

		Map<String, Object> data = new LinkedHashMap<>();
		data.put("giftId", "1");
		data.put("uid", uid);
		data.put("quantity", 1);
		data.put("nickname", userinfo.getNickname());
		data.put("avanta", userinfo.getAvanta());
		data.put("liveRoomUid", "6");
		MessagePacketData packetData = new MessagePacketData();
		packetData.setType(MessageType.REDIS_PROXY_MESSAGE_NEW_GIFT_EVENT);
		packetData.setContent(data);

		String str = QuickHelper.object2json(packetData);
		logger.info(str);
		//将送礼物的消息发送到 redis
		int result = redisUtils.lSet(key1, packetData);
		//List<Object> list = redisUtils.rangeList(key2,0,100);

		return R.response(ResponseCode.NONE).put("result", data);
	}

	@GetMapping(value = "get_live_stat")
	@ApiOperation("查询指定直播流的推流和播放信息")
	public R getLiveStat(){

		try{
			Credential cred = new Credential("AKIDqsgGYay6SXu3vWnjw4wKUP3D2LPfrgKT", "NVQBG9m9csraZWGjwztXvJsEPKfBRqlo");

			HttpProfile httpProfile = new HttpProfile();
			httpProfile.setEndpoint("live.tencentcloudapi.com");

			ClientProfile clientProfile = new ClientProfile();
			clientProfile.setHttpProfile(httpProfile);

			LiveClient client = new LiveClient(cred, "", clientProfile);

			DescribeStreamPlayInfoListRequest req = new DescribeStreamPlayInfoListRequest();


			DescribeStreamPlayInfoListResponse resp = client.DescribeStreamPlayInfoList(req);

			System.out.println(DescribeStreamPlayInfoListResponse.toJsonString(resp));
			return R.ok(resp);
		} catch (TencentCloudSDKException e) {
			System.out.println(e.toString());
			return R.error(e.toString());
		}

//		Map<String,Object> paramMap=new HashMap<>();
//		paramMap.put("cmd"," ");
//		paramMap.put("interface","Get_LiveStat");
//		paramMap.put("Param.n.page_no",1);
//		paramMap.put("Param.n.page_size",20);
//		Integer time=DateUtils.getSecondTimestamp(new Date());
//		paramMap.put("t",time);
//		paramMap.put("sign", DigestUtil.md5Hex("456456"+time));
//		String url="http://statcgi.video.qcloud.com/common_access";
//		String result= HttpUtil.get(url, paramMap);

	}

}